package com.bgs.eat.commodityOrder.service.impl;

import com.bgs.eat.commodity.entity.CommodityEntity;
import com.bgs.eat.commodity.mapper.CommodityMapper;
import com.bgs.eat.commodityOrder.entity.CommodityOrderEntity;
import com.bgs.eat.commodityOrder.mapper.CommodityOrderMapper;
import com.bgs.eat.commodityOrder.service.CommodityOrderService;
import com.bgs.eat.config.CommonResult;
import com.bgs.eat.rider.entity.Riderinformation;
import com.bgs.eat.rider.entity.UserProtal;
import com.bgs.eat.rider.mapper.riderMapper;
import com.bgs.eat.rider.mapper.riderinformationMapper;
import com.bgs.eat.userAddress.entity.UserAddressEntity;
import com.bgs.eat.userAddress.service.UserAddressService;
import com.bgs.eat.userProtal.entity.UserProtalEntity;
import com.bgs.eat.userProtal.service.UserProtalService;
import com.bgs.eat.utils.MapDistance;
import com.bgs.eat.utils.RanNum;
import com.bgs.eat.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName CommodityOrderServiceImpl
 * @Description TODO
 * @Author lzy
 * @Date 2022/10/19 19:01
 **/
@Service
public class CommodityOrderServiceImpl implements CommodityOrderService {

    @Autowired
    private riderMapper riderMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private riderinformationMapper riderinformationMapper;

    @Autowired
    private CommodityOrderMapper commodityOrderMapper;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private UserProtalService userProtalService;

    @Autowired
    private RedisUtil redisUtil;

    /* *
     * @Author: beisheng
     * @Descriprion: 根据当前骑手所在县查询所有订单
     * @Date: 2022/10/21 15:25
     * @Return: com.bgs.eat.config.CommonResult
     * @Param: [phone]
     */

    @Override
    public CommonResult findAllOrders(String phone,String riderLat,String riderLng,Integer id,Integer status) throws ParseException {
        Example example = new Example(Riderinformation.class);
        Example.Criteria criteria = example.createCriteria();

        Example exampleUser = new Example(UserProtal.class);
        Example.Criteria criteriaUser = exampleUser.createCriteria();

        criteriaUser.andEqualTo("phone",phone);
        UserProtal userProtal = riderMapper.selectOneByExample(exampleUser);

        criteria.andEqualTo("userProtalId",userProtal.getId());
        Riderinformation riderinformation = riderinformationMapper.selectOneByExample(example);

        Example exampleOrder = new Example(CommodityOrderEntity.class);
        Example.Criteria criteriaOrder = exampleOrder.createCriteria();
        if(id!=null){
            criteriaOrder.andEqualTo("riderId",riderinformation.getId());
        }
        if(status!=null){
            criteriaOrder.andEqualTo("distributionStatus",status);
        }
        if(id == null){
            criteriaOrder.andEqualTo("distributionStatus",2);
        }
        criteriaOrder.andEqualTo("distributionMode",1);
        criteriaOrder.andEqualTo("orderStatus",2);
        criteriaOrder.andEqualTo("countyId",riderinformation.getCountyId());
        List<CommodityOrderEntity> commodityOrders = commodityOrderMapper.selectByExample(exampleOrder);
        List<CommodityOrderEntity> commodityOrderEntities = new ArrayList<>();
        if(commodityOrders!=null){
         for (int i =0;i<commodityOrders.size();i++) {
             CommonResult allAdderss = userAddressService.getAllAdderssById(commodityOrders.get(i).getUserAddressId());
             UserAddressEntity userAddressEntity = new ObjectMapper().convertValue(allAdderss.getObj(), UserAddressEntity.class);
             commodityOrders.get(i).setUserAddress(userAddressEntity.getAddress());
             commodityOrders.get(i).setRiderShopDistance(MapDistance.getDistance(riderLat, riderLng, commodityOrders.get(i).getShopLat(), commodityOrders.get(i).getShopLng()));
             commodityOrders.get(i).setUserShopDistance(MapDistance.getDistance(commodityOrders.get(i).getShopLat(), commodityOrders.get(i).getShopLng(), commodityOrders.get(i).getUserLat(), commodityOrders.get(i).getUserLng()));
             commodityOrders.get(i).setTotalDistance(String.valueOf(Double.valueOf(commodityOrders.get(i).getRiderShopDistance()) + Double.valueOf(commodityOrders.get(i).getUserShopDistance())));
             commodityOrders.get(i).setRiderShopDistance(commodityOrders.get(i).getRiderShopDistance().substring(0,4));
             commodityOrders.get(i).setUserShopDistance(commodityOrders.get(i).getUserShopDistance().substring(0,4));
             commodityOrders.get(i).setTotalDistance(commodityOrders.get(i).getTotalDistance().substring(0,4));
             SimpleDateFormat format = new SimpleDateFormat("HH:mm");
             String format1 = format.format(new Date());
             //一天的毫秒数
             long nd = 1000*60*60*24;
             //一小时的毫秒数
             long nh = 1000*60*60;
             //一分钟的毫秒数
             long nm = 1000*60;
             //一秒钟的毫秒数
             long ns = 1000;
             long s = format.parse(commodityOrders.get(i).getDeliveryTime()).getTime() - format.parse(format1).getTime();
             long min = s%nd%nh/nm;
             commodityOrders.get(i).setEstimatedTime(String.valueOf(min));
             Double aDouble = Double.valueOf(commodityOrders.get(i).getRiderShopDistance());
             double v = aDouble * 1000 / 200;
             if(v<=20 && Integer.valueOf(commodityOrders.get(i).getEstimatedTime())>0){
                 commodityOrderEntities.add(commodityOrders.get(i));
             }
         }
        }
        return CommonResult.ok(commodityOrderEntities);
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 骑手抢单/取货/配送完成
     * @Date: 2022/10/24 8:45
     * @Return: com.bgs.eat.config.CommonResult
     * @Param: [id, orderId]
     */

    @Override
    public CommonResult snatchOrders(Integer id,Integer orderId,Integer type,String riderLat,String riderLng) throws ParseException {
        Example example = new Example(Riderinformation.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userProtalId",id);
        Riderinformation riderinformation = riderinformationMapper.selectOneByExample(example);

        Example exampleOrder = new Example(CommodityOrderEntity.class);
        Example.Criteria criteriaOrder = exampleOrder.createCriteria();
        criteriaOrder.andEqualTo("id",orderId);
        CommodityOrderEntity commodityOrderEntity1 = commodityOrderMapper.selectOneByExample(exampleOrder);
        CommodityOrderEntity commodityOrderEntity = new CommodityOrderEntity();
        BeanUtils.copyProperties(commodityOrderEntity1,commodityOrderEntity);
        commodityOrderEntity.setRiderId(riderinformation.getId());
        if(commodityOrderEntity1.getRamainingItem()=="已超时"){
            commodityOrderEntity.setDistributionStatus(6);
        }else {
            commodityOrderEntity.setDistributionStatus(type);
        }
        commodityOrderEntity.setRiderShopDistance(MapDistance.getDistance(riderLat, riderLng,  commodityOrderEntity.getShopLat(),  commodityOrderEntity.getShopLng()));
        commodityOrderEntity.setUserShopDistance(MapDistance.getDistance( commodityOrderEntity.getShopLat(),  commodityOrderEntity.getShopLng(),commodityOrderEntity.getUserLat(), commodityOrderEntity.getUserLng()));
        commodityOrderEntity.setTotalDistance(String.valueOf(Double.valueOf( commodityOrderEntity.getRiderShopDistance()) + Double.valueOf(commodityOrderEntity.getUserShopDistance())));
        commodityOrderEntity.setRiderShopDistance(commodityOrderEntity.getRiderShopDistance().substring(0,4));
        commodityOrderEntity.setUserShopDistance(commodityOrderEntity.getUserShopDistance().substring(0,4));
        commodityOrderEntity.setTotalDistance( commodityOrderEntity.getTotalDistance().substring(0,4));

        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        String format1 = format.format(new Date());
        //一天的毫秒数
        long nd = 1000*60*60*24;
        //一小时的毫秒数
        long nh = 1000*60*60;
        //一分钟的毫秒数
        long nm = 1000*60;
        //一秒钟的毫秒数
        long ns = 1000;
        long s = format.parse(commodityOrderEntity.getDeliveryTime()).getTime() - format.parse(format1).getTime();
        long min = s%nd%nh/nm;
        commodityOrderEntity.setEstimatedTime(String.valueOf(min));
        commodityOrderEntity.setUpdateTime(new Date());
        if("".equals(commodityOrderEntity.getRamainingItem()) || commodityOrderEntity.getRamainingItem()==null){
            commodityOrderEntity.setRamainingItem(commodityOrderEntity.getEstimatedTime());
        }
        int i = commodityOrderMapper.updateByExample(commodityOrderEntity, exampleOrder);
        if(i>0){
            return CommonResult.ok();
        }else {
            return CommonResult.error("999");
        }

    }

    /* *
     * @Author: beisheng
     * @Descriprion: 每过一分钟减剩余时间一分钟
     * @Date: 2022/10/25 15:10
     * @Return: com.bgs.eat.config.CommonResult
     * @Param: [commodityOrderEntity]
     */

    @Override
    public CommonResult updateTime(CommodityOrderEntity commodityOrderEntity) {

        Example exampleOrder = new Example(CommodityOrderEntity.class);
        Example.Criteria criteriaOrder = exampleOrder.createCriteria();
        criteriaOrder.andEqualTo("id",commodityOrderEntity.getId());
        int i = commodityOrderMapper.updateByExample(commodityOrderEntity, exampleOrder);
        if(i>0){
            return CommonResult.ok();
        }else {
            return CommonResult.error("999");
        }
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 根据骑手ID查询今日订单
     * @Date: 2022/10/27 15:32
     * @Return: com.bgs.eat.config.CommonResult
     * @Param: [riderId]
     */

    @Override
    public CommonResult getTodayOrder(Integer riderId) {

        Example example = new Example(CommodityOrderEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("riderId",riderId);
        criteria.andEqualTo("distributionStatus",4);
        criteria.orEqualTo("distributionStatus",5);
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = yearFormat.format(new Date());
        System.out.println("format::::"+format);
        criteria.andLike("updateTime","%"+format+"%");
        List<CommodityOrderEntity> commodityOrderEntities = commodityOrderMapper.selectByExample(example);
        for (int i = 0; i < commodityOrderEntities.size(); i++) {
            if(commodityOrderEntities.get(i).getDistributionStatus()==4){
                commodityOrderEntities.get(i).setFlag("未到账");
            }else {
                commodityOrderEntities.get(i).setFlag("已到账");
            }
        }
        return CommonResult.ok(commodityOrderEntities);
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 查询历史订单
     * @Date: 2022/10/28 9:19
     * @Return: com.bgs.eat.config.CommonResult
     * @Param: [id, status, stutus1]
     */
    @Override
    public CommonResult findAllhistoryOrders(Integer id,Integer status, Integer stutus1) {
        Example exampleRider = new Example(Riderinformation.class);
        Example.Criteria criteriaRider = exampleRider.createCriteria();
        criteriaRider.andEqualTo("userProtalId",id);
        Riderinformation riderinformation = riderinformationMapper.selectOneByExample(exampleRider);

        Example exampleOrder = new Example(CommodityOrderEntity.class);
        Example.Criteria criteriaOrder = exampleOrder.createCriteria();
        if(status!=0 && stutus1!=0){
            criteriaOrder.andEqualTo("distributionStatus",status);
            criteriaOrder.orEqualTo("distributionStatus",stutus1);
        }else {
            if(status!=0){
                criteriaOrder.andEqualTo("distributionStatus",status);
            }
            if(stutus1!=0){
                criteriaOrder.andEqualTo("distributionStatus",stutus1);
            }
        }
        criteriaOrder.andEqualTo("riderId",riderinformation.getId());

        List<CommodityOrderEntity> commodityOrderEntities = commodityOrderMapper.selectByExample(exampleOrder);

        for (CommodityOrderEntity commodityOrderEntity : commodityOrderEntities) {
            CommonResult allAdderss = userAddressService.getAllAdderssById(commodityOrderEntity.getUserAddressId());
            UserAddressEntity userAddressEntity = new ObjectMapper().convertValue(allAdderss.getObj(), UserAddressEntity.class);
            commodityOrderEntity.setUserAddress(userAddressEntity.getAddress());
            CommonResult allUserById = userProtalService.getAllUserById(userAddressEntity.getUserProtalId());
            UserProtalEntity userProtalEntity = new ObjectMapper().convertValue(allUserById.getObj(), UserProtalEntity.class);
            commodityOrderEntity.setUserName(userProtalEntity.getUserName());
            if(commodityOrderEntity.getDistributionStatus() ==5){
                commodityOrderEntity.setOrderFlag("准时送达");
            }else {
                commodityOrderEntity.setOrderFlag("已超时");
            }
        }
        return CommonResult.ok(commodityOrderEntities);
    }

    /**
    * @Description 提交订单时获取预计到达时间（门户用户端）
    * @Author lzy
    * @Date 2022/10/29 9:57
    * @Return com.bgs.eat.config.CommonResult
    * @param userLat
    * @param userLng
    * @param shopLat
    * @param shopLng
    * @param sumMealTime 总出餐时间
    */
    @Override
    public CommonResult getDeliveryTime(String userLat, String userLng, String shopLat, String shopLng, Integer sumMealTime) {
        String distance = MapDistance.getDistance(userLat, userLng, shopLat, shopLng);
        // 计算用户到商家的时间
        double deliveryTimeMinute = Double.valueOf(distance) * 1000 / 200 + 20;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        Date date = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.setTime(date);
        // 将当前时间加上 用户到商家店铺的时间 算出预计送达时间
        nowTime.add(Calendar.MINUTE, (int) deliveryTimeMinute + sumMealTime);
        Date deliveryTime = nowTime.getTime();
        String format = sdf.format(deliveryTime);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("deliveryTime", format);
        map.put("distance", distance);
        return CommonResult.ok(map);
    }

    /**
    * @Description 用户提交商品订单（门户用户端）
    * @Author lzy
    * @Date 2022/10/30 19:36
    * @Return com.bgs.eat.config.CommonResult
    * @param commodityOrderEntity
    */
    @Override
    public CommonResult submitCommodityOrder(CommodityOrderEntity commodityOrderEntity) {
        HashMap<Object, Object> resultMap = new HashMap<>();
        List<CommodityEntity> sumList = commodityOrderEntity.getSumList();
        ArrayList<Object> checkSumList = new ArrayList<>();
        // todo 校验商品库存是否够
        for (CommodityEntity commodityEntity : sumList) {
            Integer sum = commodityMapper.checkCommoditySum(commodityEntity.getId());
            if (sum < commodityEntity.getSum()) {
                commodityEntity.setSum(sum);
                checkSumList.add(commodityEntity);
            }
        }
        if (checkSumList.size() > 0) {
            resultMap.put("code", 401);
            resultMap.put("sumList", sumList);
            return CommonResult.ok(resultMap);
        } else {
            // 订单状态
            commodityOrderEntity.setOrderStatus(1);
            // 订单创建时间
            commodityOrderEntity.setCreateTime(new Date());
            // 生成时间戳订单编号
            String randomNum = RanNum.createRanNum();
            commodityOrderEntity.setOrderNumber(randomNum);
            // 默认配送状态 未派单
            commodityOrderEntity.setDistributionStatus(1);
//        redisUtil.set(randomNum,randomNum, 900);
            return null;
        }
    }

    /**
     * @Author gpd
     * @Description 查询对应配送状态的订单信息
     * @Date 2022-10-31 下午 03:53
     * @Return com.bgs.eat.config.CommonResult

     */
    @Override
    public List<CommodityOrderEntity> getCommodityOrderList(Integer shopId, Integer distributionStatus) {
        CommodityOrderEntity  commodityOrderEntity = new CommodityOrderEntity();
        commodityOrderEntity.setShopId(shopId);
        commodityOrderEntity.setDistributionStatus(distributionStatus);
        return commodityOrderMapper.select(commodityOrderEntity);
    }

    /**
     * @Author gpd
     * @Description 商家选择配送方式
     * @Date 2022-11-01 上午 11:38
     * @Return com.bgs.eat.config.CommonResult

     */
    @Override
    public Integer choseDeliveryMethod(CommodityOrderEntity commodityOrderEntity) {
        return commodityOrderMapper.updateByPrimaryKeySelective(commodityOrderEntity);
    }
}
